package cn.yzj.openapi.dao.intf;

import cn.org.atool.fluent.mybatis.base.IBaseDao;
import cn.yzj.http.YzjHttp;
import cn.yzj.http.YzjHttpResult;
import cn.yzj.http.YzjSendConfig;
import cn.yzj.openapi.dto.DomainIconDTO;
import cn.yzj.openapi.entity.DomainIconEntity;
import cn.yzj.openapi.vo.DomainIconVO;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 地址图标
 *
 * @author gzkemays
 * @since 2022/06/18 12:40
 */
public interface DomainIconDao extends IBaseDao<DomainIconEntity> {
  String GET_ICON_API = "http://favicongrabber.com/api/grab/${DOMAIN}?pretty=true";
  String DOMAIN_PATTERN = "${DOMAIN}";

  /**
   * 根据 domain 获取图标
   *
   * @param dto dto#domain
   * @return 类型
   * @deprecated 请求不稳定
   */
  DomainIconEntity getIconByDomain(DomainIconDTO dto);

  DomainIconEntity getIconByDomainByHttp(DomainIconDTO dto);

  List<DomainIconVO> getDomainIconList(List<String> domains);
  /**
   * 获取请求地址
   *
   * @param domain 地址
   * @return api 地址
   */
  default String getIconUrl(String domain) {
    return GET_ICON_API.replace(DOMAIN_PATTERN, domain);
  }

  default List<String> createGetToHttpIcon(String domain) {
    YzjHttpResult send =
        YzjHttp.createGet(domain)
            .defaultUserAgent()
            .config(YzjSendConfig.start().document().end())
            .send();
    Document document = send.getDocument();
    List<String> links = new ArrayList<>();
    Elements headers = document.getElementsByTag("head");
    for (Element header : headers) {
      Elements children = header.children();
      for (Element child : children) {
        if (child.hasAttr("rel")) {
          String rel = child.attr("rel");
          String link;
          if (rel.contains("icon")) {
            if (StringUtils.isNotBlank(link = (child.attr("href")))) {
              if (link.startsWith("//")) {
                link = link.replaceFirst("//", "");
              } else if (link.startsWith("/")) {
                link = link.replaceFirst("/", "");
              }
              links.add(link);
            }
          }
        }
      }
    }
    if (!CollectionUtils.isEmpty(links)) {
      String prefixDomain = domain.substring(domain.indexOf("://") + 3),
          prefixHttp = domain.substring(0, domain.indexOf("://") + 3);
      prefixDomain = prefixDomain.substring(0, prefixDomain.indexOf("/"));
      String finalPrefixDomain = prefixDomain;
      return links.stream()
          .map(
              link -> {
                if (!link.startsWith("http")) {
                  String newLink = finalPrefixDomain + "/" + link;
                  if (!finalPrefixDomain.endsWith("/") && !link.startsWith("/")) {
                    newLink = finalPrefixDomain + "/" + link;
                  }
                  if (!newLink.startsWith("http")) {
                    newLink = prefixHttp + newLink;
                  }
                  return newLink;
                }
                return link;
              })
          .collect(Collectors.toList());
    }
    return links;
  }
}
